package cn.edu.fzu.homemaking.company.mq;

import javax.annotation.Resource;

import cn.edu.fzu.homemaking.company.api.OrderApi;
import cn.edu.fzu.homemaking.company.config.CompanyConfig;
import cn.edu.fzu.homemaking.company.domain.entity.Order;
import cn.edu.fzu.homemaking.company.domain.enums.OrderStatusEnum;
import cn.edu.fzu.homemaking.company.handler.OrderHandler;
import cn.edu.fzu.homemaking.company.handler.OrderSession;
import cn.edu.fzu.homemaking.helper.DingDingRobot;
import cn.edu.fzu.homemaking.helper.EmailHelper;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Component
public class OrderDealMQ {

    private static final String EMAIL_TITLE   = "订单失败通知";
    private static final String EMAIL_CONTENT = "亲爱的顾客，很抱歉通知您，您的订单处理失败。\r\n由于当前时间与约定时间不足一小时，已为您取消当前订单。\r\n失败原因为：";

    @Resource
    private List<OrderHandler>  orderHandlers;

    @Resource
    private EmailHelper         emailHelper;

    @Resource
    private OrderApi            orderApi;

    //监听order message队列
    @RabbitListener(queues = { CompanyConfig.QUEUE_ORDER })
    public void receive(Order order) {
        long now = System.currentTimeMillis();
        OrderSession session = OrderSession.build(order);
        for (OrderHandler handler : orderHandlers) {
            try {

                if (!handler.process(session)) {
                    orderApi.updateOrderStatus(order.getOrderId(), OrderStatusEnum.ORDER);

                    List<String> error = new ArrayList<>();
                    error.add("订单id：" + order.getOrderId());
                    error.add(session.error.getDesc());

                    DingDingRobot.home().send("订单处理失败", "请检查订单信息是否有误", error, null, null);
                    //如果订单处理失败并且订单要求开始时间不足1小时，则告知用户
                    if (order.getStartTime().getTime() - now < 60 * 60 * 1000) {
                        orderApi.updateOrderStatus(order.getOrderId(), OrderStatusEnum.CANCEL);
                        emailHelper.sendMail(order.getEmail(), EMAIL_TITLE, EMAIL_CONTENT + session.error.getDesc());
                    }
                    return;
                }
            } catch (Exception e) {
                List<String> error = new ArrayList<>();
                error.add("订单id：" + order.getOrderId());
                error.add(e.getMessage());
                DingDingRobot.home().send("订单处理失败", "请检查订单信息是否有误", error, null, null);
                orderApi.updateOrderStatus(order.getOrderId(), OrderStatusEnum.ORDER);
            }
        }
    }

}
